



package wviz.gui;

import javax.swing.text.*;
import java.awt.*;

/**
 * A simple word searcher which search inside a text for a word and paint hits by it's HighlightPainter. 
 * @author Mohammad Asgari
 * @version 1.0
 * @date 11-Dec-2008
 */
public class WordSearcher {
    protected JTextComponent comp;
    protected Highlighter.HighlightPainter painter;


    public WordSearcher(JTextComponent comp) {
        this.comp = comp;
        //this.painter = new UnderlineHighlighter.UnderlineHighlightPainter(Color.red);
        this.painter = new DefaultHighlighter.DefaultHighlightPainter(Color.yellow);
    }

    // Search for a word and return the offset of the
    // first occurrence. Highlights are added for all
    // occurrences found.
    public int search(String word) {
        int firstOffset = -1;
        Highlighter highlighter = comp.getHighlighter();
        highlighter.removeAllHighlights();
        if (word == null || word.equals("")) {
            return -1;
        }

        // Look for the word we are given - insensitive search
        String content;
        try {
            Document d = comp.getDocument();
            content = d.getText(0, d.getLength()).toLowerCase();
        } catch (BadLocationException e) {
            // Cannot happen
            return -1;
        }

        word = word.toLowerCase();
        int lastIndex = 0;
        int wordSize = word.length();

        while ((lastIndex = content.indexOf(word, lastIndex)) != -1) {
            int endIndex = lastIndex + wordSize;
            //check selected word is a single word or part of a word
            boolean singleWord = false;
            if (!Character.isLetter(content.charAt(endIndex))) //next character at the end of the word should not be a letter
                singleWord = true;
            if (lastIndex > 0) {
                singleWord = singleWord && !Character.isLetter(content.charAt(lastIndex -1)); //previous character should not be a letter
            }
            //todo: use user preference here for selecting whole word or part of the word
            // singleWord = preference.getInstance().getSearchPref().isHighlightSingleWords();
            if (singleWord) {
                try {
                    highlighter.addHighlight(lastIndex, endIndex, painter);
                } catch (BadLocationException e) {
                    // Nothing to do
                }
            }
            if (firstOffset == -1) {
                firstOffset = lastIndex;
            }
            lastIndex = endIndex;
        }

        return firstOffset;
    }
}